﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using System.Xml;
using System.Windows.Markup;

using System.Windows.Media.Media3D;
using _3DHouse.CustomControl;
using System.Windows.Media.Animation;
using _3DHouse.Lib;
using System.Collections;

namespace _3DHouse
{
    /// <summary>
    /// Viewer.xaml 的交互逻辑
    /// </summary>
    public partial class Viewer : Window
    {
        /// <summary>
        /// 创建查看窗口
        /// </summary>
        public Viewer()
        {
            InitializeComponent();
           
        }
        /// <summary>
        /// 使用指定的参数创建查看窗口
        /// </summary>
        /// <param name="path">户型图路径</param>
        /// <param name="name">传感器名称</param>
        /// <param name="type">传感器报警类型，根据不同类型调用不同方法</param>
        /// <param name="state">传感器状态，根据不同状态显示不同效果</param>
        public Viewer(string path,string name, AlarmType type, SensorState state)
        {
            InitializeComponent();
            LoadMap(path);
            Display(name, state, type);
        }
        //Height="500" Width="900"  MouseWheel="Window_MouseWheel" WindowStartupLocation="CenterScreen" WindowState="Maximized"
        /// <summary>
        /// 使用集合创建查看窗口
        /// </summary>
        /// <param name="path">户型图路径</param>
        /// <param name="sensors">传感器集合</param>
        public Viewer(string path, List<Sensor> sensors)
        {
            InitializeComponent();
            LoadMap(path);
            int n = 0;
            foreach (Sensor sensor in sensors)
            {
                if(n<2){
                Display(sensor.Name, sensor.State, sensor.AlarmType);}
                n++;
            }
        }
        /// <summary>
        /// 报警方法
        /// </summary>
        /// <param name="path">户型图路径</param>
        /// <param name="name">传感器名称</param>
        /// <param name="type">传感器类型，根据不同类型调用不同方法</param>
        /// <param name="state">传感器状态，根据不同状态显示不同效果</param>
        //public  void BaoJing(string path,string name, AlarmType type, SensorState state)
        //{
           
          
        //    //判断报警类型，调用不同方法。
        //    switch (type)
        //    {
        //        case AlarmType.Light: Display(name, SensorState.Alarm,type); break;
        //        case AlarmType.Voice: Display(name, SensorState.Alarm,type); break;
        //        default: break;
        //    }
        //}
       /// <summary>
       /// 多个报警器同时报警
       /// </summary>
       /// <param name="sensors">报警器列表</param>
        //public void BaoJing(string path,List<Sensor> sensors)
        //{
        //    LoadMap(path);
        //    foreach (Sensor sensor in sensors)
        //    { //判断报警类型，调用不同方法。
        //        switch (sensor.AlarmType)
        //        {
        //            case AlarmType.Light: Display(sensor.Name, SensorState.Alarm, sensor.AlarmType); break;
        //            case AlarmType.Voice: Display(sensor.Name, SensorState.Alarm, sensor.AlarmType); break;
        //            default: break;
        //        }
        //    }
        //}
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            bool? test = null;
            if (!test.HasValue) //check for a value
            {
                // Assume that IsInitialized
                // returns either true or false.
                test = open.ShowDialog();
            }
            if ((bool)test)
            {
               
                try
                {
                   
                        /* byte[] btfile = new byte[file.Length];
                         file.Read(btfile, 0, btfile.Length);
                         string ss = Encoding.UTF8.GetString(btfile);
                         StringReader stringReader = new StringReader(ss);
                         XmlReader xmlr = XmlReader.Create(stringReader);
                         Word = (Viewport3D)XamlReader.Load(xmlr);*/
                       
                        //_3DTools.TrackballDecorator tb = new TrackballDecorator();
                        //tb.Content = World;
                        //Word.MouseDown += new MouseButtonEventHandler(HitTest);
                        //三维场景添加变换
                        
                        // RotateTransform3D rotate = new RotateTransform3D(_rotation);
                        // _transform.Children.Add(rotate);
                       
                        
                        // ProjectionCamera myCamera= World.Camera as ProjectionCamera;//场景摄像机
                       // myCamera.Transform = _transform;
                       // myCamera.Position=new Point3D(-1.64,46.71,0.26);
                       // myCamera.LookDirection=new Vector3D(0.078,-2.23,-0.01);
                       // myCamera.UpDirection=new Vector3D(0.01,-0.02,-1);
                        LoadMap(open.FileName);
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        /// <summary>
        /// 加载地图
        /// </summary>
        /// <param name="fileName">地图路径</param>
        private void LoadMap(string fileName)
        {
            try
            {
                grid.Children.Clear();
                using (FileStream file = new FileStream(fileName, FileMode.Open))
                {
                    World = XamlReader.Load(file) as Viewport3D;
                    //变换组
                    Transform3DGroup _transform = new Transform3DGroup();
                    //旋转
                    RotateTransform3D rotate = new RotateTransform3D(axisAngle);
                    _transform.Children.Add(rotate);
                    //平移
                    translate = new TranslateTransform3D();
                    _transform.Children.Add(translate);
                    World.Camera.Transform = _transform;
                    northArrowCamera.Transform = rotate;
                    ModelVisual3D floor = DrawFloor.WriteFloor(World);
                    World.Children.Add(floor);
                    grid.Children.Add(World);
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

     
       //地图旋转角度
        AxisAngleRotation3D axisAngle = new AxisAngleRotation3D(new Vector3D(0, 1, 0), 0);
        private Point mLastPos;//最后点击2dz坐标
        Point mouseLastPosition;//水平旋转方向
        double mouseDeltaFactor = 1.2;//水平旋转角度
        TranslateTransform3D translate;
        Point3D hitPoint;//鼠标点击坐标      
      /// <summary>
      /// 报警方法
      /// </summary>
      /// <param name="name">报警器名称</param>
      /// <param name="state">报警器状态</param>
      /// <param name="type">报警类型</param>
        void Display(string name, SensorState state,AlarmType type)
        {
            if (grid.Children.Count > 0)
            {
               
                Viewport3D vp = grid.Children[0] as Viewport3D;       
                foreach (Visual3D elem in vp.Children)//循环Visual3D(不能是ModelVisual这样会丢失原来类型）3D对象
                {                    
                    if (elem is Sensor)
                    {
                        Sensor sensor = elem as Sensor;
                        if (sensor.Name.Equals(name))
                        {
                            //报警
                            if (state == SensorState.Alarm)
                            {
                                if (type == AlarmType.Light)//条件貌似逻辑不对，是灯光还是报警
                                {
                                    Flash(sensor);//灯光报警                              
                                }
                                //声音报警
                                if (type == AlarmType.Voice)
                                {
                                    VoiceFlash(sensor);
                                }
                            }
                            //正常
                            else if (state == SensorState.Normal)
                            {
                                GeometryModel3D geometry = sensor.Content as GeometryModel3D;
                                geometry.Material = new DiffuseMaterial(new SolidColorBrush(Colors.Green));
                            }
                            //坏
                            else if (state == SensorState.Bad)
                            {
                                GeometryModel3D geometry = sensor.Content as GeometryModel3D;
                                geometry.Material = new DiffuseMaterial(new SolidColorBrush(Colors.Black));
                            }
                            //移动视角
                            Point3D point = new Point3D(sensor.Content.Bounds.X, sensor.Content.Bounds.Y, sensor.Content.Bounds.Z);
                            MoveCamera(point);
                            break;
                        }
                       
                    }                    
                }
            }
        }
        

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
          //  Display("war1", false);
            // SaveFileDialog savedialog = new SaveFileDialog();
            //savedialog.Filter = "xaml|*.xml|所有文件|*.*";
            //if (savedialog.ShowDialog().Value)
            //{
            //    try
            //    {
            //        //创建一个文件流对象
            //        using (FileStream ms = new FileStream(savedialog.FileName, FileMode.Create))
            //        {//保存户型图图片
            //            XamlWriter.Save(World, ms);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message);
            //    }
            //}
            Vector3D lookDirection = new Vector3D(0,-1,-2);
            Vector3D upDirection = new Vector3D(0,1,0);
            Point3D worldPoint3D = new Point3D(0,12.5,26);//场景俯视点
            ProjectionCamera camera = World.Camera as ProjectionCamera;
            camera.Position = worldPoint3D;
            camera.LookDirection = lookDirection;
            camera.UpDirection = upDirection;
        }
       
      
        #region 控制场景旋转
        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {            
            if (e.LeftButton != MouseButtonState.Pressed) return;           
            Point pos = Mouse.GetPosition(World);
            mLastPos = pos;
            if (e.ClickCount == 2)
            {
                PointHitTestParameters pointparams = new PointHitTestParameters(pos);
                VisualTreeHelper.HitTest(World, null, MoveResult, pointparams);
                MoveCamera(hitPoint);
            }
        }

        private void MoveCamera(Point3D movePoint3D)
        {
            Transform3DGroup group = World.Camera.Transform as Transform3DGroup;
            
            /***/         
           
            DoubleAnimation doubleAnimationX = new DoubleAnimation();
            doubleAnimationX.BeginTime = new TimeSpan(0, 0, 0);
            doubleAnimationX.Duration = TimeSpan.FromMilliseconds(500);
            doubleAnimationX.From = translate.OffsetX;
            doubleAnimationX.To = movePoint3D.X;

            DoubleAnimation doubleAnimationY = new DoubleAnimation();
            doubleAnimationY.BeginTime = new TimeSpan(0, 0, 0);
            doubleAnimationY.Duration = TimeSpan.FromMilliseconds(500);
            doubleAnimationY.From = translate.OffsetY;
            doubleAnimationY.To = movePoint3D.Y;

            DoubleAnimation doubleAnimationZ = new DoubleAnimation();
            doubleAnimationZ.BeginTime = new TimeSpan(0, 0, 0);
            doubleAnimationZ.Duration = TimeSpan.FromMilliseconds(500);
            doubleAnimationZ.From = translate.OffsetZ;
            doubleAnimationZ.To = movePoint3D.Z;
            
            translate.BeginAnimation(TranslateTransform3D.OffsetXProperty, doubleAnimationX);
            translate.BeginAnimation(TranslateTransform3D.OffsetYProperty, doubleAnimationY);
            translate.BeginAnimation(TranslateTransform3D.OffsetZProperty, doubleAnimationZ);
            double angle = 0;
            if (movePoint3D.X > 2)
            {
                angle = -90;
            }
            else if (movePoint3D.X < -2)
            {
                angle = 90;
            }
            else if (movePoint3D.Z > 2)
            {
                angle = 180;
            }
            else if (movePoint3D.Z < 2)
            {
                angle = 0;
            }
            DoubleAnimation doubleAnimationAngle = new DoubleAnimation();
            doubleAnimationAngle.BeginTime = new TimeSpan(0, 0, 0);
            doubleAnimationAngle.Duration = TimeSpan.FromMilliseconds(500);
            doubleAnimationAngle.From = axisAngle.Angle;
            doubleAnimationAngle.To = angle;
            axisAngle.BeginAnimation(AxisAngleRotation3D.AngleProperty, doubleAnimationAngle);
            //指北针旋转
           // northRotate.Angle += angle;
            //northRotate.BeginAnimation(RotateTransform.AngleProperty, doubleAnimationAngle);
            /**/
            //MoveCam(translate.OffsetX - hitPoint.X, translate.OffsetZ - hitPoint.Z);
            // MoveCam(3);
            // MoveCam(-hitPoint.X, -hitPoint.Z); 
            //第一取原来的摸
            //double oldM = 17.670597047072292;
            //double oldM = 2.23606797749979;
            ////第二新摸
            //// ProjectionCamera camera = World.Camera as ProjectionCamera;
            //// Vector3D vNew = new Vector3D(-camera.Position.X,-camera.Position.Y,-camera.Position.Z);
            //Vector3D vNew = new Vector3D(camera.LookDirection.X, camera.LookDirection.Y, camera.LookDirection.Z);
            //double newM = Math.Sqrt(vNew.X * vNew.X + vNew.Y * vNew.Y + vNew.Z * vNew.Z);
            //double newVecX = vNew.X / newM * oldM;
            //double newVecY = vNew.Y / newM * oldM;
            //double newVecZ = vNew.Z / newM * oldM;
            //camera.LookDirection = new Vector3D(newVecX, newVecY, newVecZ);// _center - position;//设置新的观察方向
            ///***/
            //double oldCameraM = 10.670597047072292;
            //Vector3D vcamera = new Vector3D(camera.Position.X, camera.Position.Y, camera.Position.Z);
            //double cameraM = Math.Sqrt(vcamera.X * vcamera.X + vcamera.Y * vcamera.Y + vcamera.Z * vcamera.Z);
            //x = vcamera.X / cameraM * oldCameraM;
            //y = vcamera.Y / cameraM * oldCameraM;
            //z = vcamera.Z / cameraM * oldCameraM;
            //camera.Position = new Point3D(x, y, z);
        }
        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                Point newMousePosition = e.GetPosition(this);

                if (mouseLastPosition.X != newMousePosition.X)
                {
                    HorizontalTransform(mouseLastPosition.X < newMousePosition.X, mouseDeltaFactor);
                }
               
                // if (mouseLastPosition.Y != newMousePosition.Y)// change position in the horizontal direction
                //{

                //    VerticalTransform(mouseLastPosition.Y > newMousePosition.Y, mouseDeltaFactor);
                //}
                mouseLastPosition = newMousePosition;
            }
        }
        private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //mDown = false;
        }
        private void VerticalTransform(bool upDown, double angleDeltaFactor)
        {
            ProjectionCamera myCamera = World.Camera as ProjectionCamera;
            Vector3D postion = new Vector3D(myCamera.Position.X, myCamera.Position.Y, myCamera.Position.Z);
            Vector3D rotateAxis = Vector3D.CrossProduct(postion, myCamera.UpDirection);
            RotateTransform3D rt3d = new RotateTransform3D();
            AxisAngleRotation3D rotate = new AxisAngleRotation3D(rotateAxis, angleDeltaFactor * (upDown ? -1 : 1));
            rt3d.Rotation = rotate;
            Matrix3D matrix = rt3d.Value;
           // Point3D newPostition = matrix.Transform(camera.Position);
           // camera.Position = newPostition;
            //camera.LookDirection = new Vector3D(-newPostition.X, -newPostition.Y, -newPostition.Z);

            //update the up direction
            //Vector3D newUpDirection = Vector3D.CrossProduct(camera.LookDirection, rotateAxis);
           // newUpDirection.Normalize();
           // camera.UpDirection = newUpDirection;
            //大场景
            Point3D bigPostition = matrix.Transform(myCamera.Position);
            myCamera.Position = bigPostition;
           // myCamera.LookDirection = new Vector3D(-bigPostition.X, -bigPostition.Y, -bigPostition.Z);

            //update the up direction
           // Vector3D bigUpDirection = Vector3D.CrossProduct(myCamera.LookDirection, rotateAxis);
            //newUpDirection.Normalize();
           // myCamera.UpDirection = newUpDirection;
            /**/
            //计算向量
            Vector3D vOld = myCamera.LookDirection;
            Vector3D vNew = new Vector3D(-bigPostition.X, -bigPostition.Y, -bigPostition.Z);//新的向量
            //第一取原来的摸
            double oldM = Math.Sqrt(vOld.X * vOld.X + vOld.Y * vOld.Y + vOld.Z * vOld.Z);
            //第二新摸
            double newM = Math.Sqrt(vNew.X * vNew.X + vNew.Y * vNew.Y + vNew.Z * vNew.Z);
            double newVecX = vNew.X / newM * oldM;
            double newVecY = vNew.Y / newM * oldM;
            double newVecZ = vNew.Z / newM * oldM;
            myCamera.LookDirection = new Vector3D(newVecX, newVecY, newVecZ);// _center - position;//设置新的观察方向
            /**/
        }
        /// <summary>
        /// 水平旋转
        /// </summary>
        /// <param name="leftRight">方向</param>
        /// <param name="angleDeltaFactor">角度</param>
        private void HorizontalTransform(bool leftRight, double angleDeltaFactor)
        {
            ProjectionCamera myCamera= World.Camera as ProjectionCamera;//场景摄像机
            Vector3D rotateAxis = myCamera.UpDirection;//向上方向的向量
            RotateTransform3D rt3d = new RotateTransform3D();
            AxisAngleRotation3D rotate = new AxisAngleRotation3D(rotateAxis, angleDeltaFactor * (leftRight ? -1 : 1));
            rt3d.Rotation = rotate;
            
            //空间转换的矩阵，两个摄像机公用
            Matrix3D matrix = rt3d.Value;
            //变换后的坐标
            Point3D newPostition = matrix.Transform(northArrowCamera.Position);
            //给方块摄像机设置坐标
             northArrowCamera.Position = newPostition;
             northArrowCamera.LookDirection = new Vector3D(-newPostition.X, -newPostition.Y, -newPostition.Z);
            //大场景
            //变换后的坐标
            Point3D bigPostition = matrix.Transform(myCamera.Position);
            myCamera.Position = bigPostition;
            //计算向量
            Vector3D vOld = myCamera.LookDirection;
            Vector3D vNew = new Vector3D(-bigPostition.X, -bigPostition.Y, -bigPostition.Z);//新的向量
            //第一取原来的摸
            double oldM = Math.Sqrt(vOld.X * vOld.X + vOld.Y * vOld.Y + vOld.Z * vOld.Z);
            //第二新摸
            double newM = Math.Sqrt(vNew.X * vNew.X + vNew.Y * vNew.Y + vNew.Z * vNew.Z);
            double newVecX = vNew.X / newM * oldM;
            double newVecY = vNew.Y / newM * oldM;
            double newVecZ = vNew.Z / newM * oldM;
            myCamera.LookDirection = new Vector3D(newVecX, newVecY, newVecZ);// _center - position;//设置新的观察方向
        }
        private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            int n = e.Delta;
            int num = 1;
            if (n < 0)
            {
                num = -1;
            }
            PerspectiveCamera myCamera = World.Camera as PerspectiveCamera;
            ////相机位置
            var cameraPostion = myCamera.Position;
            ////相机看的方向
            var lookDirection = myCamera.LookDirection;
            /// 获取相机在3D投影的点 
            var x = cameraPostion.X + lookDirection.X * num;
            var y = cameraPostion.Y + lookDirection.Y * num;
            var z = cameraPostion.Z + lookDirection.Z * num;
            myCamera.Position = new Point3D(x, y, z);
        }
      
        #endregion
        public HitTestResultBehavior MoveResult(System.Windows.Media.HitTestResult rawresult)
        {
            RayHitTestResult rayResult = rawresult as RayHitTestResult;
            if (rayResult != null)
            {
                //命中的网格.
                RayMeshGeometry3DHitTestResult rayMeshResult = rayResult as RayMeshGeometry3DHitTestResult;
                if (rayMeshResult != null)
                {//判断是否是复合网格
                    ModelVisual3D hitModel = rayMeshResult.VisualHit as ModelVisual3D;
                    //单个网格
                    GeometryModel3D hitgeo = rayMeshResult.ModelHit as GeometryModel3D;
                    MeshGeometry3D hitmesh = hitgeo.Geometry as MeshGeometry3D;
                    Point3D p1 = hitmesh.Positions.ElementAt(rayMeshResult.VertexIndex1);//返回序列中指定索引处的元素
                    double weight1 = rayMeshResult.VertexWeight1;// 网格三角形的第一个顶点与该三角形和命中测试的相交点的相对基值，用 0 到 1 之间的值表示。
                    Point3D p2 = hitmesh.Positions.ElementAt(rayMeshResult.VertexIndex2);
                    double weight2 = rayMeshResult.VertexWeight2;
                    Point3D p3 = hitmesh.Positions.ElementAt(rayMeshResult.VertexIndex3);
                    double weight3 = rayMeshResult.VertexWeight3;

                    //点击的三维坐标点
                    Point3D prePoint = new Point3D(p1.X * weight1 + p2.X * weight2 + p3.X * weight3, p1.Y * weight1 + p2.Y * weight2 + p3.Y * weight3, p1.Z * weight1 + p2.Z * weight2 + p3.Z * weight3);
                    hitPoint = prePoint;//记录点击坐标
                }
            }
            return HitTestResultBehavior.Stop;
        }
       /// <summary>
       /// 闪烁
       /// </summary>
        void Flash(Sensor model)
        {            
            //获得模型
            //判断模型内容类型，是否是Mode3DGroup
            if (model.Content is Model3DGroup)
            {
                Model3DGroup group = model.Content as Model3DGroup;
               //循环每个子元素
                foreach (GeometryModel3D geome in group.Children)
                {
                    FlashInfo(Colors.Red, geome);     
                }
            }
            else if (model.Content is GeometryModel3D)
            {
                GeometryModel3D geometry = model.Content as GeometryModel3D;
                FlashInfo(model.AlarmColor, geometry);     
            }
           
        }

        private static void FlashInfo(Color colors, GeometryModel3D geometry)
        {
            SolidColorBrush sol = null;
            Color startColor = Colors.Black;//渐变开始颜色
            Color endColor = colors;//渐变结束颜色，获得模型报警颜色
            //判断材质是否为空
            if (geometry.Material != null)
            {
                //判断材质是哪个
                if (geometry.Material is MaterialGroup)
                {
                    MaterialGroup gruop = geometry.Material as MaterialGroup;
                    foreach (Material material in gruop.Children)
                    {
                        if (material is EmissiveMaterial)
                        {
                            EmissiveMaterial emiss = material as EmissiveMaterial;
                            if (emiss.Brush == null)
                            {
                                sol = new SolidColorBrush(endColor);
                            }
                            else
                            {
                                sol = emiss.Brush as SolidColorBrush;
                            }
                        }
                    }
                }
                else if (geometry.Material is DiffuseMaterial)
                {//材质顺序，先DiffuseMaterial
                    MaterialGroup gruop = new MaterialGroup();
                    DiffuseMaterial diff = new DiffuseMaterial(new SolidColorBrush(startColor));
                    gruop.Children.Add(diff);
                    geometry.Material = gruop;
                    EmissiveMaterial emiss = new EmissiveMaterial();
                    sol = new SolidColorBrush(endColor);
                    emiss.Brush = sol;
                    gruop.Children.Add(emiss);
                }
            }
            else
            {
                MaterialGroup gruop = new MaterialGroup();
                DiffuseMaterial diff = new DiffuseMaterial(new SolidColorBrush(startColor));
                gruop.Children.Add(diff);
                geometry.Material = gruop;
                EmissiveMaterial emiss = new EmissiveMaterial();
                sol = new SolidColorBrush(endColor);
                emiss.Brush = sol;
                gruop.Children.Add(emiss);
            }
            ColorAnimationUsingKeyFrames color = new ColorAnimationUsingKeyFrames();
            color.KeyFrames.Add(new EasingColorKeyFrame(startColor, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))));
            color.KeyFrames.Add(new EasingColorKeyFrame(endColor, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1))));
            color.BeginTime = TimeSpan.FromSeconds(0.01);
            color.RepeatBehavior = RepeatBehavior.Forever;
            sol.BeginAnimation(SolidColorBrush.ColorProperty, color);
        }
        /// <summary>
        /// 声音报警
        /// </summary>
        /// <param name="model">报警对象</param>
        void VoiceFlash(ModelVisual3D model)
        {
            //判断是否包含声音显示对象
            if (model.Children.Count > 0)
            {
                Voice voice = null;
                bool isVoice=false;
                foreach (Visual3D visual in model.Children)
                {
                    if (visual is Voice)
                    {
                         voice = visual as Voice;
                        isVoice = true;
                        break;
                    }
                }
                if (!isVoice)//没有显示对象
                {//添加
                    voice = Voice.GetVoice();
                    model.Children.Add(voice);
                    //voice.Transform
                }
                //获得动画对象ScaleTransform3D
                ScaleTransform3D scale = new ScaleTransform3D();
                
                if (voice.Transform is Transform3DGroup)//组合变换
                {
                    Transform3DGroup transGroup = voice.Transform as Transform3DGroup;
                    foreach (Transform3D trans in transGroup.Children)
                    {
                        if (trans is ScaleTransform3D)
                        {
                            scale = trans as ScaleTransform3D;
                        }                    
                    }
                }
                else //没有添加组合变换
                {
                    Transform3DGroup transGroup = new Transform3DGroup();
                    transGroup.Children.Add(scale);
                    TranslateTransform3D translate = new TranslateTransform3D(model.Content.Bounds.X + model.Content.Bounds.SizeX / 4, model.Content.Bounds.Y + model.Content.Bounds.SizeY, model.Content.Bounds.Z + model.Content.Bounds.SizeZ);
                    transGroup.Children.Add(translate);
                    voice.Transform = transGroup;
                }                
                DoubleAnimation doubleAnimationX = new DoubleAnimation();
                doubleAnimationX.BeginTime = new TimeSpan(0, 0, 0);
                doubleAnimationX.RepeatBehavior = RepeatBehavior.Forever;
                doubleAnimationX.From = 0;
                doubleAnimationX.To = 2;
                DoubleAnimation doubleAnimationZ = new DoubleAnimation();
                doubleAnimationZ.BeginTime = new TimeSpan(0, 0, 0);
                doubleAnimationZ.RepeatBehavior = RepeatBehavior.Forever;
                doubleAnimationZ.From = 0;
                doubleAnimationZ.To = 2;
                scale.BeginAnimation(ScaleTransform3D.ScaleXProperty, doubleAnimationX);
                scale.BeginAnimation(ScaleTransform3D.ScaleZProperty, doubleAnimationZ);
            }
        }
        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            Vector3D lookDirection = new Vector3D(0.07, -1.88, -1.19);
            Vector3D upDirection = new Vector3D(-0.02, 0.86, -0.03);
            Point3D worldPoint3D = new Point3D(0, 39.47, 24.98);//场景俯视点
            ProjectionCamera camera = World.Camera as ProjectionCamera;
            camera.Position = worldPoint3D;
            camera.LookDirection = lookDirection;
            camera.UpDirection = upDirection;
        }
        //窗体加载事件
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           
        }
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            Display("sensor1", SensorState.Normal, AlarmType.Light);
        }
        private void MenuItem_Click_4(object sender, RoutedEventArgs e)
        {
            Display("sensor2", SensorState.Bad,AlarmType.Light);
        }
   
    }
  
}
